import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link,
  Outlet,
  useRoutes,
  useNavigate,
} from "react-router-dom";

//import { BrowserRouter as Router,Routes,Route,Link,Outlet,useRoutes } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import NoMatch from "./NoMatch";
import Posts from "./Posts";
import Post from "./Post";
import Login from "./Login";
import Stats from "./Stats";
import PostLists from "./PostsLists";
import { useState } from "react";
//use routes instead of routes

export default function MainRouter() {
  const [user, setUser] = useState("");
  const navigate = useNavigate();

  function onLogin(user: string): boolean {
    if (user === "") {
      return false;
    }
    setUser(user);
    return true;
  }

  function MyRoutes() {
    const element = useRoutes([
      { path: "/", element: <Home /> },
      {
        path: "/posts",
        element: <Posts />,
        children: [
          { index: true, element: <PostLists /> },
          { path: ":slug", element: <Post /> },
        ],
      },
      { path: "/about", element: <About /> },
      { path: "/login", element: <Login onLogin={onLogin} /> },
      { path: "/stats", element: <Stats token={user} /> },
      { path: "*", element: <NoMatch /> },
    ]);
    return element;
  }

  function logOut() {
    setUser("");
    navigate("/");
  }
  return (
    <>
      <nav style={{ margin: 10 }}>
        <Link to="/" style={{ padding: 5 }}>
          Home
        </Link>
        <Link to="/posts" style={{ padding: 5 }}>
          Posts
        </Link>
        <Link to="/about" style={{ padding: 5 }}>
          About
        </Link>
        <span> | </span>
        {user && (
          <Link to="/stats" style={{ padding: 5 }}>
            Stats
          </Link>
        )}
        {!user && (
          <Link to="/login" style={{ padding: 5 }}>
            Login
          </Link>
        )}
        {user && (
          <span onClick={logOut} style={{ padding: 5, cursor: "pointer" }}>
            Logout
          </span>
        )}
      </nav>
      <MyRoutes />
    </>
  );
}
